<template>
    <div class="min-h-screen bg-gradient-to-b from-blue-50 to-white flex items-center justify-center px-4">
        <div class="bg-white rounded-lg shadow-xl p-8 relative overflow-hidden form-container"
            :style="{ width: isLogin ? '400px' : '500px', height: isLogin ? '400px' : '650px' }">
            <!-- 标题 -->
            <div class="text-center mb-8">
                <h1 class="text-2xl font-bold text-blue-600 mb-2">
                    {{ isLogin ? '登录' : '注册' }}
                </h1>
                <p class="text-gray-600">
                    {{ isLogin ? '欢迎来到腺样体智能检测系统' : '创建您的账户' }}
                </p>
            </div>

            <!-- 登录表单 -->
            <transition name="slide" mode="out-in">
                <form v-if="isLogin" @submit.prevent="handleLogin" class="space-y-4" key="login">
                    <div>
                        <var-input variant="outlined" v-model="loginForm.username" type="text" required
                            placeholder="请输入账号" />
                    </div>
                    <div>
                        <var-input variant="outlined" v-model="loginForm.password" type="password" required
                            placeholder="请输入密码" />
                    </div>
                    <button type="submit" :disabled="isLoading"
                        class="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-bold py-2 px-4 rounded-md transition-colors duration-300">
                        {{ isLoading ? '登录中...' : '登录' }}
                    </button>

                    <!-- 切换登录/注册 -->
                    <div class="mt-6 text-center">
                        <p class="text-sm text-gray-600">
                            {{ isLogin ? '还没有账户？' : '已有账户？' }}
                            <button type="button" @click="toggleMode" class="text-blue-600 hover:text-blue-500 font-medium">
                                {{ isLogin ? '立即注册' : '立即登录' }}
                            </button>
                        </p>
                    </div>
                </form>
                <!-- 注册表单 -->
                <form v-else @submit.prevent="handleRegister" class="space-y-4" key="register">
                    <div>
                        <var-input variant="outlined" v-model="registerForm.username" type="text" required
                            placeholder="请输入6位及以上由英文字母和数字构成的账号" />
                    </div>
                    <div>
                        <var-input variant="outlined" v-model="registerForm.password" type="password" required
                            placeholder="请输入6位及以上由英文字母和数字构成的密码" />
                    </div>
                    <div>
                        <var-input variant="outlined" v-model="registerForm.name" type="text" required
                            placeholder="请输入真实姓名" />
                    </div>
                    <div>
                        <var-input variant="outlined" v-model="registerForm.email" type="email" required
                            placeholder="请输入邮箱地址" />
                    </div>
                    <div>
                        <var-input variant="outlined" v-model="registerForm.phone" type="tel" required
                            placeholder="请输入11位手机号" maxlength="11" />
                    </div>
                    <button type="submit" :disabled="isLoading"
                        class="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-bold py-2 px-4 rounded-md transition-colors duration-300">
                        {{ isLoading ? '注册中...' : '注册' }}
                    </button>

                    <!-- 切换登录/注册 -->
                    <div class="mt-6 text-center">
                        <p class="text-sm text-gray-600">
                            {{ isLogin ? '还没有账户？' : '已有账户？' }}
                            <button type="button" @click="toggleMode" class="text-blue-600 hover:text-blue-500 font-medium">
                                {{ isLogin ? '立即注册' : '立即登录' }}
                            </button>
                        </p>
                    </div>
                </form>
            </transition>
        </div>
    </div>
</template>

<script>
// import { useUserStore } from '../../stores/user'
import authentication from '../../utils/authentication.js'
import { Snackbar, Input } from '@varlet/ui'

export default {
    name: 'Auth',
    components: {
        'var-input': Input
    },
    data() {
        return {
            isLogin: true, // 默认显示登录表单
            isLoading: false,
            // 登录表单数据
            loginForm: {
                username: '',
                password: '',
            },
            // 注册表单数据
            registerForm: {
                username: '',
                phone: '',
                email: '',
                password: '',
                name: '',
            }
        }
    },
    methods: {
        // 切换登录/注册模式
        toggleMode() {
            this.isLogin = !this.isLogin
            this.clearForms()
        },

        // 清空表单数据
        clearForms() {
            this.loginForm = {
                username: '',
                password: '',
            }
            this.registerForm = {
                username: '',
                password: '',
                name: '',
                email: '',
                phone: '',
            }
        },

        // 处理登录
        async handleLogin() {
            this.isLoading = true
            try {
                // 调用真实的登录API
                const result = await authentication.login({
                    username: this.loginForm.username,
                    password: this.loginForm.password
                })

                // 调试信息：打印API返回结果
                console.log('登录API返回结果:', result)
                
                if (result.data) {
                    // // 登录成功，保存用户信息到状态管理
                    // const userStore = useUserStore()
                    // await userStore.setUserInfo(result.data)

                    // // 如果选择了记住我，token 已通过 setUserInfo 保存
                    // // 这里可以添加额外的记住我逻辑，如保存用户名等
                    // if (this.loginForm.remember) {
                    //     localStorage.setItem('rememberUser', this.loginForm.username)
                    // }
                    // 显示登录成功消息
                    Snackbar({
                        content: '登录成功！',
                        type: 'success'
                    })
                    // 延迟跳转到主页
                    setTimeout(() => {
                        this.$router.push('/main/home')
                    }, 1500)
                } else {
                    // 登录失败，显示错误信息
                    const errorMessage = result.data?.message || result.error || '用户名或密码错误！'
                    Snackbar({
                        content: errorMessage,
                        type: 'error'
                    })
                }
            } catch (error) {
                console.error('登录失败:', error)
                Snackbar({
                    content: '登录过程中出现错误，请稍后重试',
                    type: 'error'
                })
            } finally {
                this.isLoading = false
            }
        },

        // 处理注册
        async handleRegister() {
            this.isLoading = true
            try {
                // 调用真实的注册API，参数匹配后端RegisterDto
                const result = await authentication.register({
                    username: this.registerForm.name,
                    phone: this.registerForm.phone,
                    email: this.registerForm.email,
                    password: this.registerForm.password,
                    name: this.registerForm.name,
                })

                // 根据后端返回格式处理注册结果
                if (result.data) {
                    // 注册成功，切换到登录模式
                    Snackbar({
                        content: '注册成功！请登录',
                        type: 'success'
                    })
                    // 保存用户名用于预填
                    const username = this.registerForm.name
                    // 清空注册表单
                    this.registerForm = {
                        username: '',
                        password: '',
                        name: '',
                        email: '',
                        phone: '',
                    }
                    // 延迟切换到登录模式并预填用户名
                    setTimeout(() => {
                        this.isLogin = true
                        this.loginForm.username = username
                    }, 1500)
                } else {
                    // 注册失败，显示错误信息
                    const errorMessage = result.data?.message || result.error || '注册过程中出现错误，请稍后重试'
                    Snackbar({
                        content: errorMessage,
                        type: 'error'
                    })
                }
            } catch (error) {
                console.error('注册失败:', error)
                Snackbar({
                    content: '注册过程中出现错误，请稍后重试',
                    type: 'error'
                })
            } finally {
                this.isLoading = false
            }
        },

        // 返回首页
        goHome() {
            this.$router.push('/')
        }
    }
}
</script>

<style scoped>
/* 表单容器动画效果 */
.form-container {
    transition: all 0.3s ease-in-out;
}

/* 滑动过渡效果 */
.slide-enter-active,
.slide-leave-active {
    transition: all 0.2s ease;
}

.slide-enter-from {
    transform: translateX(100%);
    opacity: 0;
}

.slide-leave-to {
    transform: translateX(-100%);
    opacity: 0;
}
</style>